﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mesuro.Equation {
	public class EqSymbolInstance : EqTerm {

		private readonly String _key;
		public String Key {
			get { return _key; }
		}

		private EqScope scope { get; set; }

		public EqSymbolInstance( String symbol )
			: base() {
			this._key = symbol;
		}

		public override EqTerm Evaluate( EqScope newScope ) {

			EqSymbol sym = newScope.FindSymbol( this );
			EqListTerm arg = (Argument == null) ? new EqListTerm() : EqListTerm.Cast( Argument.Evaluate( newScope ) );
			EqTerm result;

			if (scope == null || !scope.IsParentOf( newScope ))
				scope = newScope;

			if (sym == null) return new EqSymbolInstance( Key ) { Argument = (Argument == null) ? null : Argument.Evaluate( scope ), scope = scope };

			result = sym.Evaluate( scope, arg );

			if (result != null) return result;

			if (Argument != null && sym.SelectDefinition( 0 ))
				return new EqOperatorInstance( EqOperatorDefinition.FindOperators( " " ).First.Value ) {
					LHS = new EqSymbolInstance( Key ),
					RHS = Argument
				}.Evaluate( scope );
			else return this;
		}


		public override int ComplexityCost() {
			return 1;
		}

		public EqTerm Argument { get; set; }

		public override string ToString() {
			return _key + ((Argument == null) ? "" : '(' + Argument.ToString() + ')');
		}

	}
}
